package com.github.io.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2022/8/30 17:07
 * Description: 缓存数据控制器
 */
@RestController
@RequestMapping("/cached")
public class CachedDataController {

    @Autowired
    private RedisTemplate redisTemplate;

    // 获取所有缓存key
    @GetMapping("/list")
    public Object getKeyList() {
        Set<String> result = new HashSet<>();
        
        Set<String> keys = redisTemplate.keys("*");
        keys.forEach(key -> {
            String[] split = key.split(":");
            result.add(split[0]);
        });
        List<String> cachedKeys = Arrays.asList(result.toArray(new String[0]));
        return cachedKeys;
    }
    
    // 获取所有键名
    @GetMapping("/keys")
    public Object getKeys(String prefix){
        Set<String> keys = redisTemplate.keys(prefix+"*");
        List<String> cachedKeys = Arrays.asList(keys.toArray(new String[0]));
        return cachedKeys;
    }
    
    // 获取缓存数据
    @GetMapping("/getValue")
    public Object getValue(String key){
        Map<String, Object> result = new HashMap<>();

        Object cachedData = redisTemplate.opsForValue().get(key);
        result.put("value", cachedData);

        String[] split = key.split(":");
        if (!ObjectUtils.isEmpty(split) && split.length > 1) {
            result.put("cachedName", split[0]);
            result.put("key", split[1]);
        }
        
        return result;
    }
}
